#include "main_window.h"
#include "ui_main_window.h"
#include "product_edit_dialog.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QInputDialog>
#include <QDateTime>
#include <QMenu>
#include <QMenuBar>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    productModel(new ProductModel(this)),
    chartManager(new ChartManager(this)){

    ui->setupUi(this);
    setWindowTitle("进销存管理系统");
    setMinimumSize(1024, 768);

    setupUI();
    setupConnections();
    refreshData();
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::setupUI() {
    // 设置菜单栏
    QMenu *systemMenu = menuBar()->addMenu("系统");
    systemMenu->addAction("退出", this, &MainWindow::close);

    QMenu *helpMenu = menuBar()->addMenu("帮助");
    helpMenu->addAction("关于", this, []() {
        QMessageBox::about(nullptr, "关于", "进销存管理系统 v1.0");
    });

    // 设置状态栏
    statusBar()->showMessage("就绪");

    // 初始化产品管理标签页
    setupProductManagementTab();
    // 初始化库存管理标签页
    setupInventoryTab();
    // 初始化销售管理标签页
    setupSalesTab();
}

void MainWindow::setupConnections() {
    // 产品管理
    connect(ui->addProductBtn, &QPushButton::clicked, this, &MainWindow::onAddProductClicked);
    connect(ui->editProductBtn, &QPushButton::clicked, this, &MainWindow::onEditProductClicked);
    connect(ui->deleteProductBtn, &QPushButton::clicked, this, &MainWindow::onDeleteProductClicked);
    connect(ui->searchProductBtn, &QPushButton::clicked, this, &MainWindow::onSearchProducts);
    connect(ui->searchProductEdit, &QLineEdit::returnPressed, this, &MainWindow::onSearchProducts);

    // 库存管理
    connect(ui->stockInBtn, &QPushButton::clicked, this, &MainWindow::onStockInClicked);
    connect(ui->refreshStockBtn, &QPushButton::clicked, this, &MainWindow::refreshStockData);

    // 销售管理
    connect(ui->saleBtn, &QPushButton::clicked, this, &MainWindow::onSaleClicked);
    connect(ui->refreshSalesBtn, &QPushButton::clicked, this, &MainWindow::refreshSalesData);
}

void MainWindow::setupProductManagementTab() {
    // 设置产品表格
    ui->productTableView->setModel(productModel);
    ui->productTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->productTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->productTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->productTableView->horizontalHeader()->setStretchLastSection(true);

    // 设置列宽
    ui->productTableView->setColumnWidth(0, 60);  // ID
    ui->productTableView->setColumnWidth(1, 150); // 名称
    ui->productTableView->setColumnWidth(2, 120); // 条形码
    ui->productTableView->setColumnWidth(3, 80);  // 价格
    ui->productTableView->setColumnWidth(4, 80);  // 成本
    ui->productTableView->setColumnWidth(5, 60);  // 库存
    ui->productTableView->setColumnWidth(6, 60);  // 最低库存
}

void MainWindow::setupInventoryTab() {
    // 设置入库记录表格模型
    stockInModel = new QSqlQueryModel(this);
    ui->stockInTableView->setModel(stockInModel);
    ui->stockInTableView->horizontalHeader()->setStretchLastSection(true);

    // 设置库存查询表格模型
    stockModel = new QSqlQueryModel(this);
    ui->stockTableView->setModel(stockModel);
    ui->stockTableView->horizontalHeader()->setStretchLastSection(true);
}

void MainWindow::setupSalesTab() {
    // 销售管理标签页也使用同一个产品模型
    ui->salesProductTableView->setModel(productModel);
    ui->salesProductTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->salesProductTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->salesProductTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->salesProductTableView->horizontalHeader()->setStretchLastSection(true);

    // 设置销售记录表格模型
    salesModel = new QSqlQueryModel(this);
    ui->salesTableView->setModel(salesModel);
    ui->salesTableView->horizontalHeader()->setStretchLastSection(true);

    // 设置列宽
    ui->salesProductTableView->setColumnWidth(0, 60);  // ID
    ui->salesProductTableView->setColumnWidth(1, 150); // 名称
    ui->salesProductTableView->setColumnWidth(2, 120); // 条形码
    ui->salesProductTableView->setColumnWidth(3, 80);  // 价格
    ui->salesProductTableView->setColumnWidth(4, 80);  // 成本
    ui->salesProductTableView->setColumnWidth(5, 60);  // 库存
    ui->salesProductTableView->setColumnWidth(6, 60);  // 最低库存
}

void MainWindow::refreshData() {
    productModel->refresh();
    refreshStockData();
    refreshSalesData();
    statusBar()->showMessage("数据已刷新");
}

void MainWindow::refreshStockData() {
    // 刷新入库记录
    stockInModel->setQuery("SELECT s.id, p.name, p.barcode, s.quantity, "
                           "s.unit_price, s.total_amount, s.supplier, "
                           "s.operation_time "
                           "FROM stock_in s "
                           "JOIN products p ON s.product_id = p.id "
                           "ORDER BY s.operation_time DESC");

    // 刷新库存查询
    stockModel->setQuery("SELECT id, name, barcode, price, stock_quantity, "
                         "min_stock, category, supplier "
                         "FROM products "
                         "ORDER BY stock_quantity ASC");

    // 设置表头
    stockInModel->setHeaderData(0, Qt::Horizontal, "ID");
    stockInModel->setHeaderData(1, Qt::Horizontal, "产品名称");
    stockInModel->setHeaderData(2, Qt::Horizontal, "条形码");
    stockInModel->setHeaderData(3, Qt::Horizontal, "数量");
    stockInModel->setHeaderData(4, Qt::Horizontal, "单价");
    stockInModel->setHeaderData(5, Qt::Horizontal, "总金额");
    stockInModel->setHeaderData(6, Qt::Horizontal, "供应商");
    stockInModel->setHeaderData(7, Qt::Horizontal, "入库时间");

    stockModel->setHeaderData(0, Qt::Horizontal, "ID");
    stockModel->setHeaderData(1, Qt::Horizontal, "产品名称");
    stockModel->setHeaderData(2, Qt::Horizontal, "条形码");
    stockModel->setHeaderData(3, Qt::Horizontal, "价格");
    stockModel->setHeaderData(4, Qt::Horizontal, "库存");
    stockModel->setHeaderData(5, Qt::Horizontal, "最低库存");
    stockModel->setHeaderData(6, Qt::Horizontal, "分类");
    stockModel->setHeaderData(7, Qt::Horizontal, "供应商");
}

void MainWindow::refreshSalesData() {
    salesModel->setQuery("SELECT s.id, p.name, p.barcode, s.quantity, "
                         "s.unit_price, s.total_amount, s.customer_info, "
                         "s.operation_time "
                         "FROM sales s "
                         "JOIN products p ON s.product_id = p.id "
                         "ORDER BY s.operation_time DESC");

    salesModel->setHeaderData(0, Qt::Horizontal, "ID");
    salesModel->setHeaderData(1, Qt::Horizontal, "产品名称");
    salesModel->setHeaderData(2, Qt::Horizontal, "条形码");
    salesModel->setHeaderData(3, Qt::Horizontal, "数量");
    salesModel->setHeaderData(4, Qt::Horizontal, "单价");
    salesModel->setHeaderData(5, Qt::Horizontal, "总金额");
    salesModel->setHeaderData(6, Qt::Horizontal, "客户信息");
    salesModel->setHeaderData(7, Qt::Horizontal, "销售时间");
}

// 产品管理槽函数
void MainWindow::onAddProductClicked() {
    ProductEditDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        Product product = dialog.getProductData();
        if (productModel->addProduct(product)) {
            statusBar()->showMessage("产品添加成功");
            refreshData();
        } else {
            QMessageBox::warning(this, "错误", "添加产品失败");
        }
    }
}

void MainWindow::onEditProductClicked() {
    QModelIndexList selection = ui->productTableView->selectionModel()->selectedRows();
    if (selection.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择一个产品");
        return;
    }

    int productId = productModel->data(selection.first().siblingAtColumn(0)).toInt();
    ProductEditDialog dialog(this, productId);
    if (dialog.exec() == QDialog::Accepted) {
        Product product = dialog.getProductData();
        if (productModel->updateProduct(product)) {
            statusBar()->showMessage("产品更新成功");
            refreshData();
        } else {
            QMessageBox::warning(this, "错误", "更新产品失败");
        }
    }
}

void MainWindow::onDeleteProductClicked() {
    QModelIndexList selection = ui->productTableView->selectionModel()->selectedRows();
    if (selection.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择一个产品");
        return;
    }

    int productId = productModel->data(selection.first().siblingAtColumn(0)).toInt();
    QString productName = productModel->data(selection.first().siblingAtColumn(1)).toString();

    int ret = QMessageBox::question(this, "确认删除",
                                    QString("确定要删除产品 '%1' 吗？").arg(productName),
                                    QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        if (productModel->deleteProduct(productId)) {
            statusBar()->showMessage("产品删除成功");
            refreshData();
        } else {
            QMessageBox::warning(this, "错误", "删除产品失败");
        }
    }
}

void MainWindow::onSearchProducts() {
    QString keyword = ui->searchProductEdit->text().trimmed();
    QString field = ui->searchFieldComboBox->currentText();

    QString filter;
    if (field == "产品名称") {
        filter = QString("name LIKE '%%1%'").arg(keyword);
    } else if (field == "条形码") {
        filter = QString("barcode LIKE '%%1%'").arg(keyword);
    } else if (field == "分类") {
        filter = QString("category LIKE '%%1%'").arg(keyword);
    } else if (field == "供应商") {
        filter = QString("supplier LIKE '%%1%'").arg(keyword);
    }

    productModel->setFilter(filter);
    statusBar()->showMessage(QString("搜索完成，找到 %1 个产品").arg(productModel->rowCount()));
}

// 库存管理槽函数
void MainWindow::onStockInClicked() {
    QModelIndexList selection = ui->productTableView->selectionModel()->selectedRows();
    if (selection.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择一个产品");
        return;
    }

    int productId = productModel->data(selection.first().siblingAtColumn(0)).toInt();
    QString productName = productModel->data(selection.first().siblingAtColumn(1)).toString();
    double currentPrice = productModel->data(selection.first().siblingAtColumn(3)).toDouble();

    bool ok;
    int quantity = QInputDialog::getInt(this, "入库操作",
                                        QString("请输入 '%1' 的入库数量:").arg(productName),
                                        1, 1, 10000, 1, &ok);
    if (!ok) return;

    double unitPrice = QInputDialog::getDouble(this, "入库价格",
                                               "请输入入库单价:", currentPrice,
                                               0.01, 100000, 2, &ok);
    if (!ok) return;

    QString supplier = QInputDialog::getText(this, "供应商", "请输入供应商名称:");

    // 执行入库操作
    QSqlDatabase::database().transaction();

    try {
        QSqlQuery query;

        // 插入入库记录
        query.prepare("INSERT INTO stock_in (product_id, quantity, unit_price, "
                      "total_amount, supplier, operator_id) "
                      "VALUES (?, ?, ?, ?, ?, 1)");
        query.addBindValue(productId);
        query.addBindValue(quantity);
        query.addBindValue(unitPrice);
        query.addBindValue(quantity * unitPrice);
        query.addBindValue(supplier);

        if (!query.exec()) {
            throw std::runtime_error("插入入库记录失败");
        }

        // 更新产品库存
        query.prepare("UPDATE products SET stock_quantity = stock_quantity + ?, "
                      "updated_time = CURRENT_TIMESTAMP WHERE id = ?");
        query.addBindValue(quantity);
        query.addBindValue(productId);

        if (!query.exec()) {
            throw std::runtime_error("更新产品库存失败");
        }

        QSqlDatabase::database().commit();
        statusBar()->showMessage("入库操作成功完成");
        refreshData();

    } catch (const std::exception &e) {
        QSqlDatabase::database().rollback();
        QMessageBox::critical(this, "错误", e.what());
    }
}

// 销售管理槽函数
void MainWindow::onSaleClicked() {
    // 在销售管理标签页中使用销售产品表格的选择
    QModelIndexList selection = ui->salesProductTableView->selectionModel()->selectedRows();
    if (selection.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择一个产品");
        return;
    }

    int productId = productModel->data(selection.first().siblingAtColumn(0)).toInt();
    QString productName = productModel->data(selection.first().siblingAtColumn(1)).toString();
    int currentStock = productModel->data(selection.first().siblingAtColumn(5)).toInt();
    double salePrice = productModel->data(selection.first().siblingAtColumn(3)).toDouble();

    if (currentStock <= 0) {
        QMessageBox::warning(this, "警告", "该产品库存不足");
        return;
    }

    bool ok;
    int quantity = QInputDialog::getInt(this, "销售操作",
                                        QString("请输入 '%1' 的销售数量 (库存: %2):").arg(productName).arg(currentStock),
                                        1, 1, currentStock, 1, &ok);
    if (!ok) return;

    double unitPrice = QInputDialog::getDouble(this, "销售价格",
                                               "请输入销售单价:", salePrice,
                                               0.01, 100000, 2, &ok);
    if (!ok) return;

    QString customerInfo = QInputDialog::getText(this, "客户信息", "请输入客户信息(可选):");

    // 执行销售操作
    QSqlDatabase::database().transaction();

    try {
        QSqlQuery query;

        // 插入销售记录
        query.prepare("INSERT INTO sales (product_id, quantity, unit_price, "
                      "total_amount, customer_info, operator_id) "
                      "VALUES (?, ?, ?, ?, ?, 1)");
        query.addBindValue(productId);
        query.addBindValue(quantity);
        query.addBindValue(unitPrice);
        query.addBindValue(quantity * unitPrice);
        query.addBindValue(customerInfo);

        if (!query.exec()) {
            throw std::runtime_error("插入销售记录失败");
        }

        // 更新产品库存
        query.prepare("UPDATE products SET stock_quantity = stock_quantity - ?, "
                      "updated_time = CURRENT_TIMESTAMP WHERE id = ?");
        query.addBindValue(quantity);
        query.addBindValue(productId);

        if (!query.exec()) {
            throw std::runtime_error("更新产品库存失败");
        }

        QSqlDatabase::database().commit();
        statusBar()->showMessage("销售操作成功完成");
        refreshData();

    } catch (const std::exception &e) {
        QSqlDatabase::database().rollback();
        QMessageBox::critical(this, "错误", e.what());
    }
}
void MainWindow::setupReportsTab() {
    // 设置日期范围选择
    QDate currentDate = QDate::currentDate();
    ui->startDateEdit->setDate(currentDate.addDays(-30));  // 默认最近30天
    ui->endDateEdit->setDate(currentDate);
    ui->yearComboBox->setCurrentText(QString::number(currentDate.year()));

    // 初始化图表容器
    setupChartContainers();

    // 首次刷新图表
    refreshCharts();
}

void MainWindow::setupChartContainers() {
    // 销售统计图表
    QChartView *salesChartView = new QChartView();
    salesChartView->setRenderHint(QPainter::Antialiasing);
    QVBoxLayout *salesLayout = new QVBoxLayout(ui->salesChartWidget);
    salesLayout->addWidget(salesChartView);

    // 产品销量排行图表
    QChartView *rankingChartView = new QChartView();
    rankingChartView->setRenderHint(QPainter::Antialiasing);
    QVBoxLayout *rankingLayout = new QVBoxLayout(ui->rankingChartWidget);
    rankingLayout->addWidget(rankingChartView);

    // 库存分布图表
    QChartView *inventoryChartView = new QChartView();
    inventoryChartView->setRenderHint(QPainter::Antialiasing);
    QVBoxLayout *inventoryLayout = new QVBoxLayout(ui->inventoryChartWidget);
    inventoryLayout->addWidget(inventoryChartView);

    // 利润分析图表
    QChartView *profitChartView = new QChartView();
    profitChartView->setRenderHint(QPainter::Antialiasing);
    QVBoxLayout *profitLayout = new QVBoxLayout(ui->profitChartWidget);
    profitLayout->addWidget(profitChartView);

    // 月度趋势图表
    QChartView *trendChartView = new QChartView();
    trendChartView->setRenderHint(QPainter::Antialiasing);
    QVBoxLayout *trendLayout = new QVBoxLayout(ui->trendChartWidget);
    trendLayout->addWidget(trendChartView);
}

void MainWindow::refreshCharts() {
    QDate startDate = ui->startDateEdit->date();
    QDate endDate = ui->endDateEdit->date();
    int year = ui->yearComboBox->currentText().toInt();

    // 更新销售统计图表
    QLayout *salesLayout = ui->salesChartWidget->layout();
    if (salesLayout && salesLayout->count() > 0) {
        QChartView *chartView = qobject_cast<QChartView*>(salesLayout->itemAt(0)->widget());
        if (chartView) {
            chartView->setChart(chartManager->createSalesChart(startDate, endDate));
        }
    }

    // 更新产品销量排行图表
    QLayout *rankingLayout = ui->rankingChartWidget->layout();
    if (rankingLayout && rankingLayout->count() > 0) {
        QChartView *chartView = qobject_cast<QChartView*>(rankingLayout->itemAt(0)->widget());
        if (chartView) {
            chartView->setChart(chartManager->createProductSalesRankingChart(startDate, endDate));
        }
    }

    // 更新库存分布图表
    QLayout *inventoryLayout = ui->inventoryChartWidget->layout();
    if (inventoryLayout && inventoryLayout->count() > 0) {
        QChartView *chartView = qobject_cast<QChartView*>(inventoryLayout->itemAt(0)->widget());
        if (chartView) {
            chartView->setChart(chartManager->createInventoryDistributionChart());
        }
    }

    // 更新利润分析图表
    QLayout *profitLayout = ui->profitChartWidget->layout();
    if (profitLayout && profitLayout->count() > 0) {
        QChartView *chartView = qobject_cast<QChartView*>(profitLayout->itemAt(0)->widget());
        if (chartView) {
            chartView->setChart(chartManager->createProfitAnalysisChart(startDate, endDate));
        }
    }

    // 更新月度趋势图表
    QLayout *trendLayout = ui->trendChartWidget->layout();
    if (trendLayout && trendLayout->count() > 0) {
        QChartView *chartView = qobject_cast<QChartView*>(trendLayout->itemAt(0)->widget());
        if (chartView) {
            chartView->setChart(chartManager->createMonthlySalesTrendChart(year));
        }
    }

    statusBar()->showMessage("图表已刷新");
}

void MainWindow::onDateRangeChanged() {
    refreshCharts();
}

void MainWindow::onYearChanged() {
    refreshCharts();
}
